package com.yu.mail.starter.utils;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程工具类
 * @author yuhh
 * @date 2019/11/28 14:50
 **/
public final class ThreadUtil {

    /**
     * 生成线程池
     * @param threadName 线程名
     * @return java.util.concurrent.ThreadPoolExecutor
     * @author yuhh
     * @date 2021/5/24 14:07
     */
    public static ThreadPoolExecutor buildThreadPool(String threadName){
        int processors = Runtime.getRuntime().availableProcessors() * 2;
        return new ThreadPoolExecutor(processors, processors, 0L,
                TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(),
                new ThreadFactoryBuilder(threadName));
    }

    /**
     * 线程工厂构造内部类
     * @author yuhh
     * @date 2019/11/28 15:28
     */
    private static class ThreadFactoryBuilder implements ThreadFactory {

        /** 线程下标 */
        private final AtomicInteger counter;
        /** 线程名 */
        private final String threadName;

        private ThreadFactoryBuilder(String threadName){
            this.threadName = threadName;
            this.counter = new AtomicInteger(1);
        }

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, threadName + "-" + counter.getAndIncrement());
        }
    }

    private ThreadUtil(){

    }
}
